from django.core.management.base import BaseCommand, CommandError
import threading
import time
import sys
from background.mysql_es_sync import sync_instance


class Command(BaseCommand):
    help = '启动MySQL到Elasticsearch的实时同步'

    def add_arguments(self, parser):
        parser.add_argument(
            '--action',
            default='start',
            choices=['start', 'stop', 'rebuild'],
            help='执行的操作: start=启动同步, stop=停止同步, rebuild=重建索引'
        )

    def handle(self, *args, **options):
        action = options['action']
        
        if action == 'start':
            self.stdout.write(self.style.SUCCESS('正在启动MySQL到ES的实时同步进程...'))

            # 初始化连接
            if not sync_instance.connect_es():
                self.stdout.write(self.style.ERROR('无法连接到Elasticsearch服务器'))
                sys.exit(1)
            
            if not sync_instance.connect_mysql():
                self.stdout.write(self.style.ERROR('无法连接到MySQL服务器或binlog配置有误'))
                sys.exit(1)
                
            # 创建线程运行同步进程
            sync_thread = threading.Thread(target=sync_instance.start_sync)
            sync_thread.daemon = True  # 设为daemon线程，这样当主进程退出时，同步线程也会退出
            sync_thread.start()
            
            self.stdout.write(self.style.SUCCESS('同步进程已启动，按Ctrl+C终止...'))
            
            try:
                # 保持命令运行，直到用户中断
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                self.stdout.write(self.style.WARNING('接收到中断信号，正在停止同步进程...'))
                sync_instance.stop_sync()
                self.stdout.write(self.style.SUCCESS('同步进程已停止'))
                
        elif action == 'stop':
            self.stdout.write(self.style.WARNING('正在停止同步进程...'))
            sync_instance.stop_sync()
            self.stdout.write(self.style.SUCCESS('同步进程已停止'))
            
        elif action == 'rebuild':
            self.stdout.write(self.style.WARNING('正在重建ES索引...'))
            success, message = sync_instance.rebuild_index()
            
            if success:
                self.stdout.write(self.style.SUCCESS(message))
            else:
                self.stdout.write(self.style.ERROR(message))
                sys.exit(1) 